import React, {useState, useEffect, useRef} from 'react'
import * as echarts from 'echarts';
import dayjs from 'dayjs'
import '../styles/chart.less'

const Chart = (props) => {
  const chartRef = useRef(null)
  const { data } = props

  useEffect(() => {
    if (data) {
      console.log('data', data)
      initChart(data)
    }
  }, [data])

  const initChart = (chartData) => {
    const myChart = echarts.init(chartRef.current);
    const colorList = {
      1: '#9AD1F5', // 流动资金
      2: '#FFBE7D', // 信用账户
      3: '#A0E8AF', // 投资理财
      4: '#C7D1DB', // 固定资产
      5: '#FFB7D5', // 充值账户
    }
    // 绘制图表
    const chartOption = {
      tooltip: {
        show: false,
        trigger: 'item'
      },
      legend: {
        orient: 'horizontal',
        left: 'left',
        top: 'top',
        textStyle: {
          padding: [0, 0, 0, 0] // [上, 右, 下, 左]：调整图例文字与图形之间的间距
        },
        formatter: function (name) {
          const total = chartData
            .filter(item => item.totalAmount !== '0.00')
            .reduce((sum, item) => sum + parseFloat(item.totalAmount), 0)

          const current = chartData.find(item => item.name === name)
          // if (!current || current.totalAmount === '0.00') return name

          const percent = ((parseFloat(current.totalAmount) / total) * 100).toFixed(1)
          return `${name}（${percent === '0.0' ? '0' : percent}%）`
        }
      },
      series: [
        {
          type: 'pie',
          center: ['50%', '57%'],
          radius: ['50%', '80%'],
          label: {
            show: false,
            position: 'center'
          },
          emphasis: {
            label: {
              show: true,
              fontSize: 14,
              formatter: '{nameStyle|{b}}\n￥{percentStyle|{c}}',
              rich: {
                nameStyle: {
                  fontSize: 14,
                  lineHeight: 20,
                  fontWeight: 'normal',
                  color: '#333'
                },
                percentStyle: {
                  fontSize: 16,
                  lineHeight: 28, // 控制与上方文字的间距
                  fontWeight: 'bold',
                  color: '#000'
                }
              }
            }
          },
          labelLine: {
            show: false
          },
          data: chartData.filter(item => item.totalAmount !== '0.00').map(item => ({
            value: item.totalAmount,
            name: item.name,
            itemStyle: {
              color: colorList[item.id] || '#ccc'
            }
          }))
        }
      ]
    }

    myChart.setOption(chartOption)
  }

  if (!data) return null

  return <div ref={chartRef} className="chartPie"></div>
}

export default Chart;